package com.example.Arithmetic.Lettcode;

import com.example.Arithmetic.Arithmetic.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 日期：2023/10/14
 * 时间：15:23
 * 描述：二叉树的最大深度
 */
public class E04Lettcode104 {

    /**
     * @param root
     * @return int
     * 递归
     */
    public int maxDepth1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return Integer.max(maxDepth1(root.left), maxDepth1(root.right)) + 1;
    }

    /**
     * @param root
     * @return int
     * 广度搜索
     */
    public int maxDepth2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int count = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            count++;
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll.left==null&&poll.right==null){
                    return count;
                }
                if (poll.left != null) {
                    queue.offer(poll.left);
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                }
            }
        }
        return count;
    }

    public static void main(String[] args) {
        E04Lettcode104 e04Lettcode144 = new E04Lettcode104();
        TreeNode root = new TreeNode(
                new TreeNode(new TreeNode(4), 2, new TreeNode(7))
                , 1,
                new TreeNode(new TreeNode(5), 3, new TreeNode(6)));
        int i = e04Lettcode144.maxDepth2(root);
        System.out.println(i);
    }
}

